/**
 * 用户模块 store
 */
import router from "../../router";

import * as localKeys from "../../utils/keysManage/localKeys";
import * as sessionKeys from "../../utils/keysManage/sessionKeys";

import { dealImgUrl } from "../../utils/common";
import { disconnectSocket } from "../../utils/webSocket";
import { getById } from "../../api/users/users.api.js";

const { USER_INFO, TOKEN } = localKeys;

// 清空缓存不需要清空的 localKeys
const notClearLocalKeys = [localKeys.REMEMBER_PASSWORD];
// 清空缓存不需要清空的 sessionKeys
const notClearSessionKeys = [
  sessionKeys.SIDE_BAR_COLLAPSE,
  sessionKeys.IS_FULL_SCREEN,
  sessionKeys.APP_VERSION,
];

const initUserInfo = () => {
  return {
    id: "",
    username: "",
    nickname: "",
    avatarUrl: "",
    avatar: "",
    orgId: "",
    permissions: [],
  };
};

const state = {
  userInfo: window.localStorage.getItem(USER_INFO)
    ? JSON.parse(window.localStorage.getItem(USER_INFO))
    : initUserInfo(), // 用户信息
  hasLogin: !!window.localStorage.getItem(USER_INFO), // 是否处于登录状态
  token: window.localStorage.getItem(TOKEN) || "",
};

const mutations = {
  refreshToken(state, token) {
    if (!token) {
      return console.error("refreshToken error: token can not be null");
    }
    state.token = token;
    window.localStorage.setItem(TOKEN, state.token);
  },

  // 储存登录信息
  setUserInfo(state, userInfo) {
    if (!userInfo) {
      return console.error("setUserInfo error: userInfo can not be null");
    }
    // 处理头像相对路径
    userInfo.avatarUrl = dealImgUrl(userInfo.avatar);
    state.userInfo = userInfo;
    if (userInfo.token) {
      state.token = userInfo.token;
    }
    window.localStorage.setItem(USER_INFO, JSON.stringify(userInfo));
  },

  // 存储用户信息, 并储存登录状态
  login(state, userInfo) {
    if (!userInfo) {
      return console.error("setUserInfo error: userInfo can not be null");
    }
    state.hasLogin = true;
    // 处理头像相对路径
    userInfo.avatarUrl = dealImgUrl(userInfo.avatar);
    state.userInfo = userInfo;
    state.token = userInfo.token;
    window.localStorage.setItem(TOKEN, state.token);
    window.localStorage.setItem(USER_INFO, JSON.stringify(userInfo));
  },

  logout(state) {
    console.log("退出登录");
    state.hasLogin = false;
    state.userInfo = initUserInfo();
    state.token = "";
    Object.keys(sessionKeys).forEach((key) => {
      if (!notClearSessionKeys.includes(sessionKeys[key])) {
        window.sessionStorage.removeItem(sessionKeys[key]);
      }
    });
    Object.keys(localKeys).forEach((key) => {
      if (!notClearLocalKeys.includes(localKeys[key])) {
        window.localStorage.removeItem(localKeys[key]);
      }
    });
    // 断开webSocket连接
    disconnectSocket();
    router.replace("/login");
  },
};

const getters = {};

const actions = {
  getUserInfo({ state, commit }) {
    return new Promise((resolve, reject) => {
      getById({
        id: state.userInfo.id,
      })
        .then((res) => {
          commit("setUserInfo", res.data);
          resolve(res);
        })
        .catch((err) => {
          console.error("getUserInfo error: ", err);
          reject(err);
        });
    });
  },
};

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations,
};
